/*
 * Copyright (c) 2019 Mike Penz
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mikepenz.iconics.sample.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.element.VectorElement;
import ohos.agp.utils.Color;
import ohos.agp.window.service.DisplayManager;
import ohos.miscservices.pasteboard.PasteData;
import ohos.miscservices.pasteboard.SystemPasteboard;

import com.mikepenz.iconics.Iconics;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.sample.PlaygroundAbility;
import com.mikepenz.iconics.sample.ResourceTable;
import com.mikepenz.iconics.sample.item.IconItem;
import com.mikepenz.iconics.sample.provider.GenericModelProvider;
import com.mikepenz.iconics.sample.provider.IconItemProvider;
import com.mikepenz.iconics.sample.views.PopupWindowDialog;
import com.mikepenz.iconics.typeface.ITypeface;
import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial;
import com.mikepenz.iconics.view.IconicsImageView;

import java.util.Comparator;
import java.util.List;

import hollowsoft.slidingdrawer.OnDrawerCloseListener;
import hollowsoft.slidingdrawer.OnDrawerOpenListener;
import hollowsoft.slidingdrawer.SlidingDrawer;

/**
 * 主页面图标展示和搜索功能
 *
 * @since 2021-06-16
 */
public class MainAbilitySlice extends AbilitySlice implements PopupWindowDialog.Popcheckstatus {
    private ListContainer listContainer;
    private IconItemProvider iconItemProvider;
    private GenericModelProvider mGenericModelProvider;
    private ListContainer iconListView;
    private Component component;
    private Component componentbg;
    private Text textshowleft;
    private Text textshow;
    private Text textshowpoptop;
    private Text textshowpopbottom;
    private Text textsearch;
    private Text textclear;
    private Text texttitle;
    private DirectionalLayout dltoptitle;
    private SlidingDrawer drawer1;
    private IconicsImageView floatIconImage;
    private TextField textfieldtop;

    private PopupWindowDialog popupWindowDialog;
    private boolean brm = false;
    private boolean sd = false;
    private boolean rfb = false;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        getWindow().setStatusBarColor(Color.getIntColor("#D32F2F"));
        initView1();
        initView2();
        initTextFieldListener();
        initIconicsList();
        initDrawerLayout();
    }

    private void initView1() {
        dltoptitle = (DirectionalLayout) findComponentById(ResourceTable.Id_dl_toptitle);
        drawer1 = (SlidingDrawer) findComponentById(ResourceTable.Id_slide);
        component = findComponentById(ResourceTable.Id_component);
        componentbg = findComponentById(ResourceTable.Id_component_bg);
        floatIconImage = (IconicsImageView) findComponentById(ResourceTable.Id_float_image);
        drawer1.setOnDrawerCloseListener(new OnDrawerCloseListener() {
            @Override
            public void onDrawerClosed() {
                componentbg.setVisibility(Component.HIDE);
                iconListView.setEnabled(true);
            }
        });
        drawer1.setOnDrawerOpenListener(new OnDrawerOpenListener() {
            @Override
            public void onDrawerOpened() {
                componentbg.setVisibility(Component.VISIBLE);
                iconListView.setEnabled(false);
            }
        });
        componentbg.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component var1) {
                drawer1.animateClose();
            }
        });
        texttitle = (Text) findComponentById(ResourceTable.Id_text_title);
        texttitle.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component var1) {
            }
        });
    }

    private void initView2() {
        textshow = (Text) findComponentById(ResourceTable.Id_text_show);
        textshow.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component var1) {
                textfieldtop.clearFocus();
                dltoptitle.setVisibility(Component.VISIBLE);
                iconItemProvider.onSearch(null);
            }
        });
        textshowleft = (Text) findComponentById(ResourceTable.Id_text_showleft);
        textshowleft.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component var1) {
                drawer1.animateOpen();
            }
        });
        textshowpoptop = (Text) findComponentById(ResourceTable.Id_text_showpoptop);
        textshowpoptop.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component var1) {
                popWindowShow();
            }
        });
        textshowpopbottom = (Text) findComponentById(ResourceTable.Id_text_showpopbottom);
        textshowpopbottom.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component var1) {
                popWindowShow();
            }
        });
        textsearch = (Text) findComponentById(ResourceTable.Id_text_search);
        textsearch.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component var1) {
                dltoptitle.setVisibility(Component.HIDE);
                textfieldtop.requestFocus();
                textfieldtop.simulateClick();
            }
        });
        textclear = (Text) findComponentById(ResourceTable.Id_text_clear);
        textclear.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component var1) {
                textfieldtop.setText("");
            }
        });
        textfieldtop = (TextField) findComponentById(ResourceTable.Id_textfield_top);
    }

    private void initTextFieldListener() {
        VectorElement vectorElementleft = new VectorElement(getContext(), ResourceTable.Graphic_ic_baseline_search_24);
        VectorElement vectorElementright = new VectorElement(getContext(), ResourceTable.Graphic_ic_baseline_clear_24);
        textfieldtop.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String str, int i0, int i1, int i2) {
                if ("".equals(str)) {
                    textclear.setAroundElements(null, null, null, null);
                    textfieldtop.setAroundElements(vectorElementleft, null, null, null);
                } else {
                    textclear.setAroundElements(null, null, vectorElementright, null);
                    textfieldtop.setAroundElements(null, null, null, null);
                }
                iconItemProvider.onSearch(str);
            }
        });
    }

    private void popWindowShow() {
        popupWindowDialog = new PopupWindowDialog(this, component, this, brm, sd, rfb);
        popupWindowDialog.setSize(750, 850);
        popupWindowDialog.setAutoClosable(true);
        popupWindowDialog.setTransparent(true);
        popupWindowDialog.setBackColor(new Color(Color.getIntColor("#00000000")));
        popupWindowDialog.show();
    }

    private void initIconicsList() {
        iconListView = (ListContainer) findComponentById(ResourceTable.Id_list);
        iconListView.addScrolledListener(new Component.ScrolledListener() {
            @Override
            public void onContentScrolled(Component cp, int i0, int i1, int i2, int i3) {
                hidePopupIconImage();
            }
        });
        iconItemProvider = new IconItemProvider(this, iconListView);
        iconItemProvider.setOnItemClickedListener(new IconItemProvider.OnItemClickedListener() {
            @Override
            public void onItemClicked(int position, Component cp) {
                showPopupIconImage(listContainer, cp, position);
            }
        });
        iconListView.setLongClickable(false);
        iconListView.setItemProvider(iconItemProvider);
    }

    private void hidePopupIconImage() {
        floatIconImage.setVisibility(Component.INVISIBLE);
    }

    private void showPopupIconImage(ListContainer mlistContainer, Component mcomponent, int position) {
        int left = mcomponent.getLeft();
        Component componentParent = (Component) mcomponent.getComponentParent();
        int top = componentParent.getTop() + mlistContainer.getTop() + mlistContainer.getMarginTop()
            + mlistContainer.getPaddingTop();
        top += AttrHelper.vp2px(60, this);
        int showTop = top + componentParent.getHeight();
        int showBottom = showTop + floatIconImage.getHeight();
        int screenHeight = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes().height;
        boolean topToBottom = true;
        if (showBottom > screenHeight) {
            showTop = top - floatIconImage.getHeight();
            topToBottom = false;
        }
        floatIconImage.setTranslationX(left);
        floatIconImage.setTranslationY(showTop);
        IconItem item = (IconItem) iconItemProvider.getItem(position);
        String icon = item.getIcon();
        IconicsDrawable drawable = new IconicsDrawable(floatIconImage, this, icon);
        addToClipboard(drawable);
        if (drawable != null) {
            drawable.setPaddingPx(AttrHelper.vp2px(8, this));
            drawable.setBackgroundColor(new Color(0xDDFFFFFF));
            drawable.setBackgroundContourColor(new Color(0xDD000000));
            drawable.setBackgroundContourWidthPx(4);
            drawable.setRoundCornerSize(AttrHelper.vp2px(12, this));
            floatIconImage.setIcon(drawable);
        }
        int animateY = AttrHelper.vp2px(8, this);
        animateY = topToBottom ? animateY : -animateY;
        floatIconImage.createAnimatorProperty().moveFromY(showTop - animateY).moveToY(showTop)
            .alphaFrom(0f).alpha(1)
            .setDuration(100).start();
        floatIconImage.setVisibility(Component.VISIBLE);
    }

    private void addToClipboard(IconicsDrawable drawable) {
        if (drawable.getIcon() != null) {
            PasteData pasteData = new PasteData();
            pasteData.addTextRecord(drawable.getIcon().getFormattedName());
            SystemPasteboard.getSystemPasteboard(this).setPasteData(pasteData);
        }
    }

    private void initDrawerLayout() {
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_main);
        List<ITypeface> list = getFontData();
        mGenericModelProvider = new GenericModelProvider(list, this);
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer mlistContainer, Component mcomponent, int position, long var4) {
                String fontName = list.get(position).getFontName();
                changeTypeface(position, fontName);
                drawer1.animateClose();
                iconItemProvider.refreshData(list.get(position));
            }
        });
        listContainer.setLongClickable(false);
        listContainer.setItemProvider(mGenericModelProvider);
        for (int i = 0; i < list.size(); i++) {
            ITypeface typeface = list.get(i);
            if (typeface.getFontName().equals(GoogleMaterial.getInstance().getFontName())) {
                String fontName = typeface.getFontName();
                changeTypeface(i, fontName);
                getUITaskDispatcher().delayDispatch(new Runnable() {
                    @Override
                    public void run() {
                        iconItemProvider.refreshData(typeface);
                    }
                }, 200);
                break;
            }
        }
    }

    private void changeTypeface(int position, String fontName) {
        mGenericModelProvider.setChangepos(position);
        mGenericModelProvider.notifyDataChanged();
        texttitle.setText(fontName);
    }

    private List<ITypeface> getFontData() {
        List<ITypeface> list = Iconics.getInstance().getRegisteredFonts();
        list.sort(new Comparator<ITypeface>() {
            @Override
            public int compare(ITypeface t1, ITypeface t2) {
                return t1.getFontName().compareTo(t2.getFontName());
            }
        });
        return list;
    }

    @Override
    public void randomize(boolean randomize) {
        iconItemProvider.setRandomize(randomize);
        iconItemProvider.notifyDataChanged();
        brm = randomize;
        popupWindowDialog.destroy();
    }

    @Override
    public void shadow(boolean shadow) {
        iconItemProvider.setShadow(shadow);
        iconItemProvider.notifyDataChanged();
        sd = shadow;
        popupWindowDialog.destroy();
    }

    @Override
    public void rfb(boolean mrfb) {
        Iconics.getInstance().setRespectFontBoundsDefault(mrfb);
        iconItemProvider.respectFontBounds();
        iconItemProvider.notifyDataChanged();
        this.rfb = mrfb;
        popupWindowDialog.destroy();
    }

    @Override
    public void clike() {
        Intent mintentanother = new Intent();
        Operation moperationanother = new Intent.OperationBuilder()
            .withDeviceId("")
            .withBundleName(getBundleName())
            .withAbilityName(PlaygroundAbility.class)
            .build();
        mintentanother.setOperation(moperationanother);
        startAbility(mintentanother);
        popupWindowDialog.destroy();
    }
}
